<?php

namespace App\Listeners;

use App\Events\LeaveCar;
use App\Models\ParkingTimesCollection;
use App\Selection;
use Carbon\Carbon;
use Illuminate\Contracts\Queue\ShouldQueue;

/**
 * 停车时长统计
 *
 * Class AddFlowNumber
 * @package App\Listeners
 */
class ParkingTimeCount implements ShouldQueue
{

    public function handle(LeaveCar $event)
    {
        $park_code = $event->data->park_code;
        $dateTime = Carbon::createFromTimestamp($event->data->out_time);
        $hour = Carbon::create($dateTime->year, $dateTime->month, $dateTime->day, $dateTime->hour);

        //取车场类型
        $carType = $event->data->vpl_color;

        $config = Selection::where('params',$carType)->where('parent_id',185)->first();
        $type = $config ? $config->id : 188;

        $parkTime = ParkingTimesCollection::firstOrNew(
            [
                'park_code' => $park_code,
                'hour' => $hour,
                'type' =>$type
            ],
            [
                'total'=>0
            ]
        );

        $field = $this->initFiled(ceil($event->data->parking_duration/60));

        $parkTime->{$field}+=1;

        $parkTime->total+=1;

        $parkTime->save();
        return true;

    }


    /**
     * 计算停车时长范围
     *
     * @return string
     */
    private function initFiled($time)
    {
        $time = ceil($time);
        if($time>0 && $time<=30) return 'time_0_30';
        if($time>30 && $time<=60) return 'time_30_60';

        for ($i=60;$i<1440;$i+=60) {
            if($time>$i && $time<=$i+60 ) return 'time_'.$i.'_'.($i+60);
        }

        return 'time_1440';
    }
}
